from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.permissions import IsAuthenticated
from .authentications import generate_jwt, JWTAuthentication, GLOBAL_USERS, SimpleUser


# 登录函数
class LoginView(APIView):
    def post(self, request):
        username = request.data.get("username")
        password = request.data.get("password")

        if not username or not password:
            return Response({"error": "用户名和密码不能为空"}, status=status.HTTP_400_BAD_REQUEST)

        # 验证用户名和密码
        if username in GLOBAL_USERS and GLOBAL_USERS[username]["password"] == password:
            user = SimpleUser(GLOBAL_USERS[username])
            token = generate_jwt(user)
            return Response(
                {
                    "message": "登录成功",
                    "token": token,
                    "user": {"id": user.id, "username": user.username},
                }
            )
        else:
            return Response({"error": "用户名或密码错误"}, status=status.HTTP_401_UNAUTHORIZED)


# 首页接口（无需token）
class HomeView(APIView):
    def get(self, request):
        return Response(
            {
                "message": "欢迎来到首页",
                "description": "这是一个公开的接口，无需token即可访问",
                "status": "active",
                "version": "1.0.0",
            }
        )


# 个人中心接口（需要token验证）
class ProfileView(APIView):
    authentication_classes = [JWTAuthentication]
    permission_classes = [IsAuthenticated]

    def get(self, request):
        user = request.user
        return Response(
            {
                "message": "个人中心数据",
                "user": {"id": user.id, "username": user.username},
                "description": "JWT,请求成功!!",
            }
        )
